import { createApp } from 'vue'
import Toast from '../components/Toast.vue'

let toastInstance = null
let toastApp = null

const showToast = (message, type = 'success', duration = 3000) => {
    // 如果已经有toast实例，先移除
    if (toastInstance) {
        toastApp.unmount()
        toastInstance.remove()
    }

    // 创建容器
    const container = document.createElement('div')
    document.body.appendChild(container)

    // 创建Vue应用实例
    toastApp = createApp(Toast, {
        message,
        type,
        duration
    })

    // 挂载
    toastInstance = container
    const instance = toastApp.mount(container)

    // 显示toast
    instance.show()

    // 自动清理
    setTimeout(() => {
            if (toastApp && toastInstance) {
                toastApp.unmount()
                toastInstance.remove()
                toastInstance = null
                toastApp = null
            }
        }, duration + 500) // 额外500ms用于动画
}

export const toast = {
    success: (message, duration) => showToast(message, 'success', duration),
    error: (message, duration) => showToast(message, 'error', duration),
    info: (message, duration) => showToast(message, 'info', duration),
    warning: (message, duration) => showToast(message, 'warning', duration)
}

export default toast